package channelManager

import (
	"net"
	"sync"
)

var (
	skt2ctx sync.Map
	skt2key sync.Map
	key2ctx sync.Map
)

func Insert(ctx net.Conn) {
	skt2ctx.Store(ctx.RemoteAddr().String(), ctx)
}

func SetServiceKey(ctx net.Conn, serviceKey string) {
	skt2ctx.Store(ctx.RemoteAddr().String(), ctx)
	skt2key.Store(ctx.RemoteAddr().String(), serviceKey)
	key2ctx.Store(serviceKey, ctx)
}

func GetContextByServiceKey(serviceKey string) net.Conn {
	val, ok := key2ctx.Load(serviceKey)
	if !ok {
		return nil
	}

	return val.(net.Conn)
}

func GetServiceKeyByRemoteAddr(sktAddr string) string {
	val, ok := skt2key.Load(sktAddr)
	if !ok {
		return ""
	}

	return val.(string)
}

func getContextByRemoteAddr(sktAddr string) net.Conn {
	val, ok := skt2ctx.Load(sktAddr)
	if !ok {
		return nil
	}
	return val.(net.Conn)
}

func RemoveByRemoteAddr(sktAddr string) {
	key, ok := skt2key.Load(sktAddr)
	if ok {
		key2ctx.Delete(key)
	}

	skt2ctx.Delete(sktAddr)
	skt2key.Delete(sktAddr)
}

func removeByServiceKey(serviceKey string) {
	val, ok := key2ctx.Load(serviceKey)
	if ok {
		ctx := val.(net.Conn)
		adrr := ctx.RemoteAddr().String()

		skt2ctx.Delete(adrr)
		skt2key.Delete(adrr)
	}

	key2ctx.Delete(serviceKey)
}
